#!/usr/bin/env python3
"""
邮箱密码加密工具
使用 Fernet 对称加密来安全存储邮箱密码
"""

import os
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

class EmailEncryption:
    """邮箱密码加密类"""
    
    def __init__(self):
        self.key = self._get_or_create_key()
        self.cipher_suite = Fernet(self.key)
    
    def _get_or_create_key(self):
        """获取或创建加密密钥"""
        # 尝试加载 .env 文件
        try:
            from dotenv import load_dotenv
            load_dotenv()
        except ImportError:
            pass
        
        # 从环境变量获取密钥
        key_str = os.getenv('EMAIL_ENCRYPT_KEY')
        
        if key_str:
            try:
                # 尝试使用现有的密钥
                return key_str.encode()
            except Exception:
                print("Warning: Invalid EMAIL_ENCRYPT_KEY, generating new key")
        
        # 生成新密钥
        key = Fernet.generate_key()
        print("=" * 60)
        print("EMAIL_ENCRYPT_KEY not found or invalid.")
        print("Please add this to your .env file:")
        print(f"EMAIL_ENCRYPT_KEY={key.decode()}")
        print("=" * 60)
        
        return key
    
    def encrypt_password(self, password: str) -> str:
        """加密密码"""
        if not password:
            return ""
        
        try:
            encrypted_password = self.cipher_suite.encrypt(password.encode())
            return base64.b64encode(encrypted_password).decode()
        except Exception as e:
            print(f"Error encrypting password: {e}")
            return ""
    
    def decrypt_password(self, encrypted_password: str) -> str:
        """解密密码"""
        if not encrypted_password:
            return ""
        
        try:
            encrypted_bytes = base64.b64decode(encrypted_password.encode())
            decrypted_password = self.cipher_suite.decrypt(encrypted_bytes)
            return decrypted_password.decode()
        except Exception as e:
            print(f"Error decrypting password: {e}")
            return ""

# 全局实例
email_encryption = EmailEncryption()
